<?php
namespace App\Services;
use GuzzleHttp\Client;
use App\Models\Users;
use App\Models\Usersinvitations;
use App\Models\Linkslistsmedias;
use App\Models\Linkslistsminapps;
use App\Services\MiniappService;
use Illuminate\Support\Facades\Redis;
use Log,Exception;

class WechatService
{
    public static function code2Session($js_code,$appid,$secret)
    {
        $client = new Client;
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$js_code.'&grant_type=authorization_code');
        $body = $response->getBody();
        return json_decode($body,true);
    }

    // 接口调用凭证
    public static function getToken($appid,$secret)
    {
        $client = new Client;
        $response = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
        $body = $response->getBody();
        return json_decode($body,true);
    }

    // 获取可以自动缓存的token
    public static function getTokenRedis($appid,$secret)
    {
        try{
            $token = MiniappService::miniappAccessToken($appid,$secret);
            if (!isset($token["access_token"])) return ["status"=>"error","msg"=>"外链异常,请检查小程序信息是否正确！"];
            return ["status"=>"success","msg"=>"获取成功！","access_token"=>$token["access_token"]];
        } catch (Exception $error) {
            try{
                $message = $error->getMessage();
                $message = json_decode(str_replace("Request access_token fail: ", "", $message));
                if ($message->errcode == 40013) return ["status"=>"error","msg"=>"小程序Appid错误,请确认Appid正确且小程序已上线！"];
                if ($message->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($message->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                Log::info("\r\getTokenRedis start\r\n".json_encode($message)."\r\getTokenRedis end");
                return ["status"=>"error","msg"=>"生成Scheme错误,请联系客服处理！"];
            } catch (Exception $nerror) {
                Log::info("getTokenRedis---");
                Log::info($error->getMessage());
                Log::info($nerror);
                Log::info("getTokenRedis---");
            }
        }
    }

    // 把媒体文件上传到微信服务器,3天内有效
    public static function uploadTempMedia($access_token,$img,$links_id)
    {
        $img_name = substr($img,66);
        $medias = Linkslistsmedias::getLastMedia($links_id,$img_name);
        // 如果已过期则提前100秒查询生成
        if (empty($medias) || strtotime($medias->created_at) <= (strtotime("-3 day")+100)) {
        	$client = new Client;
        	$deleteimg = false;
        	// 如果是远程图片,先下载
        	if(strpos($img,"http:") !== false || strpos($img,"https:") !== false){
        		$media = $client->request('get',$img)->getBody()->getContents();
        		file_put_contents("images/".$img_name ,$media);
        		$deleteimg = true;
    		}

            $response = $client->request('POST',  'https://api.weixin.qq.com/cgi-bin/media/upload?type=image&access_token='.$access_token, ['multipart' => [
            		[
    		            'name'     => 'media',
    		            'contents' => fopen("images/".$img_name, 'r'),
    		        ],
                ]
            ]);

            $body = $response->getBody();

            if ($deleteimg) {
                try {
                    unlink("images/".$img_name);
                } catch (Exception $e) {

                }
            }
            $wechatUploadInfo = json_decode($body,true);

            if (isset($wechatUploadInfo["errcode"])) {
            	return "";
            } else {
                // 保存数据,下次直接调用
                Linkslistsmedias::insertLinksListsMedia($links_id,$img_name,$wechatUploadInfo["media_id"],$wechatUploadInfo["created_at"]);
            	return $wechatUploadInfo["media_id"];
            }
        } else {
            return $medias->media_id;
        }
    }

    // 微信接收客服首次绑定
    public static function servicesFirstSetting($signature,$timestamp,$nonce,$echostr)
    {
        $token = "RwWsRl5nxNxLl3";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if ($tmpStr == $signature ) {
            return $echostr;
        } else {
            return false;
        }
    }

    // 获取客服参数
    public static function getServiceParams($msg,$openid,$ToUserName,$links_id)
    {
        $minapps = Linkslistsminapps::getLinksListsMinappsByOriginalId($ToUserName);
        if (empty($minapps)) return ["status"=>"error","msg"=>"小程序未配置！"];
        $tokeninfo = self::getTokenRedis($minapps->appid,$minapps->secret);
        if ($tokeninfo["status"] == "success") {
            $access_token = $tokeninfo["access_token"];
        } else {
            return $tokeninfo;
        }

        if ($msg["type"] == 1) {
            $params = ['touser' => $openid,'msgtype' => 'text','text' => ['content'=>$msg['text']]];
        } elseif ($msg["type"] == 2) {
            $media_id = self::uploadTempMedia($access_token,$msg["text"],$links_id);
            if (empty($media_id)) return ["status"=>"error","msg"=>"素材上传不成功！"];
            $params = ['touser' => $openid,'msgtype' => 'image','image' => ['media_id'=>$media_id]];
        } elseif ($msg["type"] == 3) {
            $params = ['touser' => $openid,'msgtype' => 'link','link' => ['title'=>$msg['text']['title'],'description'=>$msg['text']['description'],'url'=>$msg['text']['url'],'thumb_url'=>$msg['text']['thumb_url']]];
        } else {
            $thumb_media_id = self::uploadTempMedia($access_token,$msg['text']['img'],$links_id);
            if (empty($thumb_media_id)) return ["status"=>"error","msg"=>"素材上传不成功！"];
            $params = ['touser' => $openid,'msgtype' => 'link','text' => '','image' => '','link' => '','miniprogrampage' => ['title'=>$msg['text']['title'],'pagepath'=>$msg['text']['pagepath'],'thumb_media_id'=>$thumb_media_id]];
        }
        $info = self::sendServiceInfo($access_token,$params);
        // 图片素材不行,删除下次重新发
        if (isset($info["errcode"]) && $info["errcode"] == 40007) {
            if ($msg["type"] == 2) {
                $img_name = substr($msg["text"],66);
            } else if ($msg["type"] == 4) {
                $img_name = substr($msg['text']['img'],66);
            }
            Linkslistsmedias::deleteMedia($links_id,$img_name);
        }
}

    // 发送客服消息
    public static function sendServiceInfo($access_token,$params)
    {
        $client = new Client;
        $response = $client->request('POST',  'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token, [
        	'body' => json_encode($params,JSON_UNESCAPED_UNICODE),
        	'headers' => [
                'Content-type'=> 'application/json',
                'Accept'=>'application/json'
            ]]);

        $body = $response->getBody();
        return json_decode($body,true);
    }

    // 获得jsapi_ticket
    public static function getTicket($appid,$access_token)
    {
        $ticketInfo = Redis::get("wechat_ticket_".$appid);
        if (empty($ticketInfo)) {
            $client = new Client;
            $response = $client->request('GET', 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&&access_token='.$access_token);
            $ticketInfo = $response->getBody()->getContents();
            Redis::setex("wechat_ticket_".$appid, 7000, $ticketInfo);
        }
        return json_decode($ticketInfo,true);
    }

    // 获取跳转小程序和路径
    public static function getLinksListsMiniapp($platfrom_type,$msg,$users_id,$links_id,$limit_pv,$notice_img)
    {
        // 私人部署小程序
        if (in_array($platfrom_type, [4,5])) {
            $msg = str_replace("'",'"',$msg);
            $msg = json_decode($msg,true);
            $mini_id = isset($msg->mini_id) ? $msg->mini_id : $msg["mini_id"];
            // 获取本小程序配置的小程序
            $minapps = Linkslistsminapps::getMiniUseableMinapps($users_id,$mini_id);
            if (!empty($minapps)) {
                $minpath = isset($msg->path) ? $msg->path : $msg["path"];
                $minpaths = parse_url($minpath);
                $path = isset($minpaths["path"]) ? $minpaths["path"] : "";
                $query = isset($minpaths["query"]) ? $minpaths["query"] : "";
            } else {
                if($platfrom_type == 4){
                    return ["status"=>"error","msg"=>"用户推广密钥版小程序,需先把小程序添加到天天外链后台！"];
                }
                $path = "/pages/index/request";
                $query = "id=".$links_id;
            }
        } elseif($platfrom_type == 12){
            if($limit_pv > 1000){
                $notice_img = str_replace("'",'"',$notice_img);
                $notice_img = json_decode($notice_img,true);
                if(!empty($notice_img)){
                    $mini_id = isset($notice_img->mini_id) ? $notice_img->mini_id : $notice_img["mini_id"];
                    // 获取本小程序配置的小程序
                    $minapps = Linkslistsminapps::getMiniUseableMinapps($users_id,$mini_id);
                }
                //如果传过来的小程序为空，则系统自动查询使用的小程序
                if(empty($minapps)){
                    $minapps = Linkslistsminapps::getUseableMinapps($users_id);
                }
                // if(empty($minapps)){
                //     return ["status"=>"error","msg"=>"用户推广公众号二维码需使用独家小程序,请联系客服部署独家小程序！"];
                // }
            }else{
                $minapps = [];
            }
            $path = "/pages/index/request";
            $query = "id=".$links_id;
        } else {
            $path = "/pages/index/request";
            $query = "id=".$links_id;
            // 获取我们给商家部署的小程序
            $minapps = Linkslistsminapps::getUseableMinapps($users_id);
        }
        if (empty($minapps)) {
            if ($limit_pv > 1000) {
                if ($platfrom_type == 1){
                    return ["status"=>"error","msg"=>"付费用户推广公众号需使用独家小程序,请联系客服部署独家小程序！"];
                    // $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(2);
                } elseif (in_array($platfrom_type, [2,3])){
                    $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(4);
                } elseif (in_array($platfrom_type, [8,9,11,13])){
                    $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(3);
                } elseif ($platfrom_type == 6){
                    $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(5);
                } else {
                    $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(1);
                }
            } else {
                $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(6);
            }
            if (empty($minapps)) {
                $minapps = Linkslistsminapps::getPlatfromUseableDefaultMinapps(6);
            }
        }

        if (empty($minapps)) return ["status"=>"error","msg"=>"当前没有可用的小程序,请联系客服！"];
        if (!empty($query)) {
            $returnpath = $path."?".$query;
        } else {
            $returnpath = $path;
        }
        return ["status"=>"success","msg"=>"创建成功！","urlscheme"=>"weixin://","data"=>["username"=>$minapps->original_id,"users_id"=>$minapps->users_id,"original_id"=>$minapps->original_id,"path"=>$returnpath,"appid"=>$minapps->appid,"miniapp_type"=>$minapps->miniapp_type]];
    }

    // 生成小程序UrlScheme
    public static function generateScheme($appid,$secret,$path,$query,$original_id,$platfrom_type,$limit_pv)
    {
        try {
            $miniapp = MiniappService::miniProgram($appid,$secret);
            $urlschemeInfo = $miniapp->url_scheme->generate(['jump_wxa' => ['path'=>$path,'query'=>$query],"is_expire"=>false,"expire_time"=>time()+3600]);
            if ($urlschemeInfo->errcode == 0) {
                $returnpath = $path;
                if (!empty($query)) $returnpath = $path."?".$query;
                return ["status"=>"success","msg"=>"创建成功！","urlscheme"=>$urlschemeInfo->openlink,"data"=>["username"=>$original_id,"original_id"=>$original_id,"path"=>$returnpath,"appid"=>$appid]];
            } else {
                if ($urlschemeInfo->errcode == 85079) return ["status"=>"error","msg"=>"小程序未发布,请发布后再创建！"];
                if ($urlschemeInfo->errcode == 40165) return ["status"=>"error","msg"=>"小程序路径path不存在,请检查小程序路径！"];
                if ($urlschemeInfo->errcode == 40002) return ["status"=>"error","msg"=>"小程序暂无生成权限,如您是个人小程序请使用点击版！"];
                if ($urlschemeInfo->errcode == 40013 && $platfrom_type == 1) {
                    if ($limit_pv > 1000) {
                        return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请切换新的独家小程序！"];
                    } else {
                        return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请联系客服处理！"];
                    }
                }
                if ($urlschemeInfo->errcode == 40013) return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请更换小程序！"];
                if ($urlschemeInfo->errcode == 40212) return ["status"=>"error","msg"=>"参数query填写错误,可以咨询客服！"];
                // 100次每秒
                if ($urlschemeInfo->errcode == 44990) return ["status"=>"error","msg"=>"生成Scheme频率过快,请稍后生成！"];
                if ($urlschemeInfo->errcode == 85400) return ["status"=>"error","msg"=>"长期有效Scheme达到生成上限10万！"];
                if ($urlschemeInfo->errcode == 45009) return ["status"=>"error","msg"=>"单天生成Scheme数量超过上限50万！"];
                if ($urlschemeInfo->errcode == 85401) return ["status"=>"error","msg"=>"参数expire_time填写错误,时间间隔大于1分钟且小于1年!"];
                if ($urlschemeInfo->errcode == 85402) return ["status"=>"error","msg"=>"参数env_version填写错误!"];
                // 本情况可能是没有设置白名单或者多个程序一直刷新Token
                if ($urlschemeInfo->errcode == 40001) return ["status"=>"error","msg"=>"AccessToken已过期,请返回重新创建！"];
                if ($urlschemeInfo->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($urlschemeInfo->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                return ["status"=>"error","msg"=>"创建外链异常,请联系客服！如您是个人小程序请使用点击版！"];
            }
        } catch (Exception $error) {
            try {
                $message = $error->getMessage();
                $message = json_decode(str_replace("Request access_token fail: ", "", $message));
                if ($message->errcode == 40013) return ["status"=>"error","msg"=>"小程序Appid错误,请确认Appid正确且小程序已上线！"];
                if ($message->errcode == 40164) return ["status"=>"error","msg"=>"小程序开启了IP白名单保护,请在「小程序后台 - 开发管理 - 开发设置」关闭IP白名单或添加IP: 39.103.171.78"];
                if ($message->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($message->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                Log::info("\r\ngenerateScheme start\r\n".json_encode($message)."\r\ngenerateScheme end");
                return ["status"=>"error","msg"=>"生成Scheme错误,请联系客服处理！"];
            } catch (Exception $e) {
                Log::info($error);
                return ["status"=>"error","msg"=>"生成Scheme错误,请联系客服处理！"];
            }
        }
    }

    // 生成小程序URL Link
    public static function generateUrlLink($appid,$secret,$path,$query,$original_id,$platfrom_type,$limit_pv)
    {
        try {
            $miniapp = MiniappService::miniProgram($appid,$secret);
            $urlschemeInfo = $miniapp->url_link->generate(['path'=>$path,'query'=>$query,"is_expire"=>false,"expire_time"=>time()+3600]);
            if ($urlschemeInfo->errcode == 0) {
                $returnpath = $path;
                if (!empty($query)) $returnpath = $path."?".$query;
                return ["status"=>"success","msg"=>"创建成功！","url_link"=>$urlschemeInfo->url_link,"data"=>["username"=>$original_id,"original_id"=>$original_id,"path"=>$returnpath,"appid"=>$appid]];
            } else {
                if ($urlschemeInfo->errcode == 85079) return ["status"=>"error","msg"=>"小程序未发布,请发布后再创建！"];
                if ($urlschemeInfo->errcode == 40165) return ["status"=>"error","msg"=>"小程序路径path不存在,请检查小程序路径！"];
                if ($urlschemeInfo->errcode == 40002) return ["status"=>"error","msg"=>"小程序暂无生成权限,如您是个人小程序请使用点击版！"];
                if ($urlschemeInfo->errcode == 40013 && $platfrom_type == 1) {
                    if ($limit_pv > 1000) {
                        return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请切换新的独家小程序！"];
                    } else {
                        return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请联系客服处理！"];
                    }
                }
                if ($urlschemeInfo->errcode == 40013) return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请更换小程序！"];
                if ($urlschemeInfo->errcode == 40212) return ["status"=>"error","msg"=>"参数query填写错误,可以咨询客服！"];
                // 100次每秒
                if ($urlschemeInfo->errcode == 44990) return ["status"=>"error","msg"=>"生成Scheme频率过快,请稍后生成！"];
                if ($urlschemeInfo->errcode == 85400) return ["status"=>"error","msg"=>"长期有效Scheme达到生成上限10万！"];
                if ($urlschemeInfo->errcode == 45009) return ["status"=>"error","msg"=>"单天生成Scheme数量超过上限50万！"];
                if ($urlschemeInfo->errcode == 85401) return ["status"=>"error","msg"=>"参数expire_time填写错误,时间间隔大于1分钟且小于1年!"];
                if ($urlschemeInfo->errcode == 85402) return ["status"=>"error","msg"=>"参数env_version填写错误!"];
                // 本情况可能是没有设置白名单或者多个程序一直刷新Token
                if ($urlschemeInfo->errcode == 40001) return ["status"=>"error","msg"=>"AccessToken已过期,请返回重新创建！"];
                if ($urlschemeInfo->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($urlschemeInfo->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                return ["status"=>"error","msg"=>"创建外链异常,请联系客服！如您是个人小程序请使用点击版！"];
            }
        } catch (Exception $error) {
            try {
                $message = $error->getMessage();
                $message = json_decode(str_replace("Request access_token fail: ", "", $message));
                if ($message->errcode == 40013) return ["status"=>"error","msg"=>"小程序Appid错误,请确认Appid正确且小程序已上线！"];
                if ($message->errcode == 40164) return ["status"=>"error","msg"=>"小程序开启了IP白名单保护,请在「小程序后台 - 开发管理 - 开发设置」关闭IP白名单或添加IP: 39.103.171.78"];
                if ($message->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($message->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                Log::info("\r\ngenerateScheme start\r\n".json_encode($message)."\r\ngenerateScheme end");
                return ["status"=>"error","msg"=>"生成URL Link错误,请联系客服处理！"];
            } catch (Exception $e) {
                Log::info($error);
                return ["status"=>"error","msg"=>"生成URL Link错误,请联系客服处理！"];
            }
        }
    }

    //生成短时间的urllink
    public static function generateShortUrlLink($appid,$secret,$path,$query)
    {
        try {
            $miniapp = MiniappService::miniProgram($appid,$secret);
            $urlschemeInfo = $miniapp->url_link->generate(['path'=>$path,'query'=>$query,"is_expire"=>true,"expire_type"=>1,"expire_interval"=>5]);
            if ($urlschemeInfo->errcode == 0) {
                $returnpath = $path;
                if (!empty($query)) $returnpath = $path."?".$query;
                return ["status"=>"success","msg"=>"创建成功！","url_link"=>$urlschemeInfo->url_link,"data"=>["path"=>$returnpath,"appid"=>$appid]];
            } else {
                if ($urlschemeInfo->errcode == 85079) return ["status"=>"error","msg"=>"小程序未发布,请发布后再创建！"];
                if ($urlschemeInfo->errcode == 40165) return ["status"=>"error","msg"=>"小程序路径path不存在,请检查小程序路径！"];
                if ($urlschemeInfo->errcode == 40002) return ["status"=>"error","msg"=>"小程序暂无生成权限,如您是个人小程序请使用点击版！"];
                if ($urlschemeInfo->errcode == 40013) return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请更换小程序！"];
                if ($urlschemeInfo->errcode == 40212) return ["status"=>"error","msg"=>"参数query填写错误,可以咨询客服！"];
                // 100次每秒
                if ($urlschemeInfo->errcode == 44990) return ["status"=>"error","msg"=>"生成Scheme频率过快,请稍后生成！"];
                if ($urlschemeInfo->errcode == 85400) return ["status"=>"error","msg"=>"长期有效Scheme达到生成上限10万！"];
                if ($urlschemeInfo->errcode == 45009) return ["status"=>"error","msg"=>"单天生成Scheme数量超过上限50万！"];
                if ($urlschemeInfo->errcode == 85401) return ["status"=>"error","msg"=>"参数expire_time填写错误,时间间隔大于1分钟且小于1年!"];
                if ($urlschemeInfo->errcode == 85402) return ["status"=>"error","msg"=>"参数env_version填写错误!"];
                // 本情况可能是没有设置白名单或者多个程序一直刷新Token
                if ($urlschemeInfo->errcode == 40001) return ["status"=>"error","msg"=>"AccessToken已过期,请返回重新创建！"];
                if ($urlschemeInfo->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($urlschemeInfo->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                return ["status"=>"error","msg"=>"创建外链异常,请联系客服！如您是个人小程序请使用点击版！"];
            }
        } catch (Exception $error) {
            try {
                $message = $error->getMessage();
                $message = json_decode(str_replace("Request access_token fail: ", "", $message));
                if ($message->errcode == 40013) return ["status"=>"error","msg"=>"小程序Appid错误,请确认Appid正确且小程序已上线！"];
                if ($message->errcode == 40164) return ["status"=>"error","msg"=>"小程序开启了IP白名单保护,请在「小程序后台 - 开发管理 - 开发设置」关闭IP白名单或添加IP: 39.103.171.78"];
                if ($message->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($message->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                Log::info("\r\ngenerateScheme start\r\n".json_encode($message)."\r\ngenerateScheme end");
                return ["status"=>"error","msg"=>"生成URL Link错误,请联系客服处理！"];
            } catch (Exception $e) {
                Log::info($error);
                return ["status"=>"error","msg"=>"生成URL Link错误,请联系客服处理！"];
            }
        }
    }

    // 根据传递过来的参数，获取有时间限制的urlscheme
    public static function generateUrlscheme($appid,$secret,$path,$query)
    {
        try {
            $miniapp = MiniappService::miniProgram($appid,$secret);
            $urlschemeInfo = $miniapp->url_scheme->generate(['jump_wxa' => ['path'=>$path,'query'=>$query],"is_expire"=>true,"expire_time"=>time()+3600]);
            if ($urlschemeInfo->errcode == 0) {
                $returnpath = $path;
                if (!empty($query)) $returnpath = $path."?".$query;
                return ["status"=>"success","msg"=>"创建成功！","urlscheme"=>$urlschemeInfo->openlink];
            } else {
                if ($urlschemeInfo->errcode == 85079) return ["status"=>"error","msg"=>"小程序未发布,请发布后再创建！"];
                if ($urlschemeInfo->errcode == 40165) return ["status"=>"error","msg"=>"小程序路径path不存在,请检查小程序路径！"];
                if ($urlschemeInfo->errcode == 40002) return ["status"=>"error","msg"=>"小程序暂无生成权限,如您是个人小程序请使用点击版！"];
                if ($urlschemeInfo->errcode == 40013) return ["status"=>"error","msg"=>"小程序生成权限被微信封禁,请更换小程序！"];
                if ($urlschemeInfo->errcode == 40212) return ["status"=>"error","msg"=>"参数query填写错误,可以咨询客服！"];
                // 100次每秒
                if ($urlschemeInfo->errcode == 44990) return ["status"=>"error","msg"=>"生成Scheme频率过快,请稍后生成！"];
                if ($urlschemeInfo->errcode == 85400) return ["status"=>"error","msg"=>"长期有效Scheme达到生成上限10万！"];
                if ($urlschemeInfo->errcode == 45009) return ["status"=>"error","msg"=>"单天生成Scheme数量超过上限50万！"];
                if ($urlschemeInfo->errcode == 85401) return ["status"=>"error","msg"=>"参数expire_time填写错误,时间间隔大于1分钟且小于1年!"];
                if ($urlschemeInfo->errcode == 85402) return ["status"=>"error","msg"=>"参数env_version填写错误!"];
                // 本情况可能是没有设置白名单或者多个程序一直刷新Token
                if ($urlschemeInfo->errcode == 40001) return ["status"=>"error","msg"=>"AccessToken已过期,请返回重新创建！"];
                if ($urlschemeInfo->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($urlschemeInfo->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                return ["status"=>"error","msg"=>"创建外链异常,请联系客服！如您是个人小程序请使用点击版！"];
            }
        } catch (Exception $error) {
            try {
                $message = $error->getMessage();
                $message = json_decode(str_replace("Request access_token fail: ", "", $message));
                if ($message->errcode == 40013) return ["status"=>"error","msg"=>"小程序Appid错误,请确认Appid正确且小程序已上线！"];
                if ($message->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
                if ($message->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
                Log::info("\r\ngenerateScheme start\r\n".json_encode($message)."\r\ngenerateScheme end");
                return ["status"=>"error","msg"=>"生成Scheme错误,请联系客服处理！"];
            } catch (Exception $e) {
                Log::info($error);
                return ["status"=>"error","msg"=>"生成Scheme错误,请联系客服处理！"];
            }
        }

    }

    // 测试用户输入的密钥是否正确
    public static function appsecretRight($appid,$secret)
    {
        $client = new Client();
        $response = $client->request('GET',"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret);
        // 获取html
        $body = $response->getBody();
        $info = json_decode($body);
        if (isset($info->errcode)){
            if ($info->errcode == 40125) return ["status"=>"error","msg"=>"小程序Appsecret错误,请修改后重新提交！"];
            if ($info->errcode == 40013) return ["status"=>"error","msg"=>"Appid错误,请确认Appid正确且小程序已上线！"];
            if ($info->errcode == 40001) return ["status"=>"error","msg"=>"AppSecret 错误或者 AppSecret 不属于这个小程序！"];
            if ($info->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
            if ($info->errcode == 40164) return ["status"=>"error","msg"=>"小程序未设置IP白名单,请在小程序后台关闭IP限制！"];
            if ($info->errcode == 50002) return ["status"=>"error","msg"=>"小程序已被注销或封禁,请修改小程序！"];
        }
        if (!isset($info->access_token))  return ["status"=>"error","msg"=>"小程序出现其他错误2！"];

        $client = new Client();
        $req = $client->request('POST', 'https://api.weixin.qq.com/wxa/generatescheme?access_token='.$info->access_token, [
            'json' => ['jump_wxa' => ['path'=>'','query'=>'']]
        ]);
        $newinfo = $req->getBody();
        $info = json_decode($newinfo);
        if ($info->errmsg == "ok") {
            $openlink = $info->openlink;
            return ["status"=>"success","msg"=>"小程序配置正确！"];
        } else {
            if ($info->errcode == 85079) return ["status"=>"error","code"=>$info->errcode,"msg"=>"小程序未上线,无法访问！"];
            if ($info->errcode == 40165) return ["status"=>"error","code"=>$info->errcode,"msg"=>"小程序路径不存在,您可以不填直接跳首页！"];
            if ($info->errcode == 40002) return ["status"=>"error","code"=>$info->errcode,"msg"=>"个人微信小程序暂无生成权限,请使用企业微信小程序！"];
            if ($info->errcode == 40013) return ["status"=>"error","code"=>$info->errcode,"msg"=>"您的小程序生成权限被封禁,请更换小程序！"];
            if ($info->errcode == 40165) return ["status"=>"error","code"=>$info->errcode,"msg"=>"参数path填写错误,可以咨询客服！"];
            if ($info->errcode == 40212) return ["status"=>"error","code"=>$info->errcode,"msg"=>"参数query填写错误,可以咨询客服！"];
            if ($info->errcode == 44990) return ["status"=>"error","code"=>$info->errcode,"msg"=>"生成Scheme频率过快,请稍后生成！"];
            if ($info->errcode == 85400) return ["status"=>"error","code"=>$info->errcode,"msg"=>"长期有效Scheme达到生成上限10万！"];
            if ($info->errcode == 45009) return ["status"=>"error","code"=>$info->errcode,"msg"=>"单天生成Scheme数量超过上限50万！"];
            // 本情况可能是没有设置白名单或者多个程序一直刷新Token
            if ($info->errcode == 40001) return ["status"=>"error","code"=>$info->errcode,"msg"=>"AccessToken已过期,请联系客服处理！"];
            if ($info->errcode == 48001) return ["status"=>"error","code"=>$info->errcode,"msg"=>"此处请添加小程序信息,您添加的是公众号！"];
            if ($info->errcode == 50002) return ["status"=>"error","code"=>$info->errcode,"msg"=>"小程序已被注销或封禁,请修改小程序！"];
            Log::info("appsecretRight------");
            Log::info($info);
            Log::info("appsecretRight------");
            return ["status"=>"error","code"=>4001,"msg"=>"小程序异常,请联系客服！"];
        }
    }

}
